<template>
  <Category :scene="scene" />
  <el-card style="margin: 10px 0px">
    <div v-show="scene == 0">
      <el-button
        type="primary"
        icon="Plus"
        style="margin: 10px 10px"
        :disabled="categoryData.c3Id ? false : true"
        @click="addAttr"
      >
        添加属性
      </el-button>
      <el-table :data="attrList">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
          border
        ></el-table-column>
        <el-table-column
          label="属性名称"
          prop="attrName"
          align="center"
        ></el-table-column>
        <el-table-column label="属性值名称" align="left">
          <template #="{ row, column, $index }">
            <el-tag
              v-for="(item, index) in row.attrValueList"
              :key="item.id"
              style="margin: 5px"
            >
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px" align="center">
          <!-- 自定义插槽 -->
          <template #="{ row, column, $index }">
            <el-button
              size="small"
              type="warning"
              icon="Edit"
              @click="updateAttr(row)"
            />
            <el-popconfirm
              :title="`您确定要删除${row.attrName}吗？`"
              width="200px"
              icon="Delete"
              @confirm="removeAttr(row.id)"
            >
              <!-- popconfirm 自定义插槽 -->
              <template #reference>
                <el-button size="small" type="danger" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="scene == 1">
      <!-- 展示提那家与修改数据的结构 -->
      <el-form inline>
        <el-form-item label="属性名称">
          <el-input
            placeholder="请输入属性名称"
            v-model="attrParams.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        @click="addAttrValue"
        type="primary"
        size="default"
        icon="Plus"
        :disabled="attrParams.attrName ? false : true"
      >
        添加属性值
      </el-button>
      <el-button type="primary" size="default" icon="Plus" @click="cancel">
        取消
      </el-button>
      <el-table
        border
        style="margin: 10px 0px"
        :data="attrParams.attrValueList"
      >
        <el-table-column
          width="80px"
          label="序号"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row, column, $index }">
            <!-- V3 ref函数式/(字符串)写法:将所有input实例动态的存储到数组中 -->
            <el-input
              :ref="(vc: any) => (inputArr[$index] = vc)"
              v-if="row.flag"
              size="small"
              placeholder="请输入属性值名称"
              v-model="row.valueName"
              @blur="toLook(row, $index)"
            ></el-input>
            <!-- div需要通过角标自动聚焦 -->
            <div v-else @click="toEdit(row, $index)">
              {{ row.valueName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="属性值操作" width="120px">
          <template #="{ row, column, $index }">
            <el-button
              size="small"
              type="danger"
              icon="Delete"
              @click="attrParams.attrValueList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 保存时必须有属性值 -->
      <el-button
        type="primary"
        size="default"
        @click="save"
        :disabled="attrParams.attrValueList.length > 0 ? false : true"
      >
        保存
      </el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import categoryDataStore from '@/store/modules/category'
import {
  reqAttr,
  reqAddOrUpdateAttr,
  reqDeleteAttr,
} from '@/api/product/attr/index'
import { ref, watch, reactive, nextTick, onBeforeUnmount } from 'vue'
import type { AttrResponseData, Attr, AttrValue } from '@/api/product/attr/type'
import { ElMessage } from 'element-plus'
import { tr } from 'element-plus/es/locale/index.js'
// 存储已有的属性与属性值
const attrList = ref<Attr[]>([])
const categoryData = categoryDataStore()
// scene=0,显示table;scene=1展示添加与修改属性结构
let scene = ref<number>(0)
// 收集新增的属性数据
let attrParams = reactive<Attr>({
  attrName: '',
  categoryId: '',
  categoryLevel: 3,
  attrValueList: [],
})
// 存储对应的el-input组件实例
let inputArr = ref<any>([])
watch(
  () => categoryData.c3Id,
  () => {
    // 清空上一次的属性集合
    attrList.value = []
    // 保证三级分类得有才能发请求
    if (!categoryData.c3Id) return
    // 获取分类属性集合
    getAttr()
  },
)
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryData
  const result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  if (result.code == 200) {
    attrList.value = result.data
  }
}

const addAttr = () => {
  // 清空上次收集到的数据
  Object.assign(attrParams, {
    attrName: '',
    categoryId: categoryData.c3Id,
    categoryLevel: 3,
    attrValueList: [],
  })
  scene.value = 1
  // 点击这个按钮的时候收集属性的三级分类ID
  attrParams.categoryId = categoryData.c3Id
}

const updateAttr = (row: Attr) => {
  scene.value = 1
  // assign 方法是浅拷贝，对于引用类型是拷贝的地址；
  // 改attrParams中的attrList 会将Row的数据也改掉，解决方法是深拷贝 全部复制一份，lodash / Json
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

const removeAttr = async (attrId: number) => {
  let result: any = await reqDeleteAttr(attrId)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}

const cancel = () => {
  scene.value = 0
}

// 添加属性值按钮的回调
const addAttrValue = () => {
  // 点击添加属性值按钮的时候，向数组添加一个属性值对象、
  attrParams.attrValueList.push({
    valueName: '',
    flag: true, // 控制每一个属性值编辑模式切换模式的切换
  })
  // 获取最后的el-input组件聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}

const toLook = (row: AttrValue, $index: number) => {
  // 无值的时候不展示DIV
  if (row.valueName.trim() == '') {
    // 删除属性值为空的元素
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }

  // 判重
  const repeat = attrParams.attrValueList.find((item: AttrValue) => {
    if (item != row) {
      return item.valueName === row.valueName
    }
  })

  if (repeat) {
    // 删除重复的元素
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值重复',
    })
    return
  }
  row.flag = false
}

const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}
// :ref=handler ==> template 模版结构发生变化时会触发
// const handler = (element) => {
//   console.log('element==>', element)
// }

// 保存按钮的回调
const save = async () => {
  // 收集参数
  // 发请求
  const result: any = await reqAddOrUpdateAttr(attrParams)
  if (result.code == 200) {
    scene.value = 0
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    })
    //获取全部已有的属性与属性值
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败',
    })
  }
}

// 路由组建销毁的时候，把仓库分类相关的数据清空
onBeforeUnmount(() => {
  categoryData.$reset()
})
</script>

<style scoped></style>
